<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <div :class="['bubble', msg.isUser ? 'user' : 'ai']">
          {{ msg.text }}
        </div>
      </div>
    </div>

    <div class="input-box">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="请输入内容..."
          type="text"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import {service_ai_openAi_chat} from '@/api/service/module/OpenAiChatMemory1'

export default {
  data() {
    return {
      inputMessage: '你好',
      messages: []
    }
  },
  methods: {
    async sendMessage() {
      const text = this.inputMessage.trim()
      if (!text) return

      // 添加用户消息到聊天记录
      this.messages.push({text, isUser: true})
      this.inputMessage = ''
      this.scrollToBottom()

      // 调用 AI 接口
      await service_ai_openAi_chat({message: text}).then(response => {
        // 假设接口返回的数据是 { answer: "AI回复内容" }
        console.info(response)
        debugger
        const reply = response.data || '没有收到回复，请稍后再试。'
        this.messages.push({text: reply, isUser: false})
        this.scrollToBottom()
      }).catch(error => {
        console.error('请求失败:', error)
        this.messages.push({text: '请求出错，请检查网络或重试。', isUser: false})
        this.scrollToBottom()
      })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.chatBox) {
          this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 90vh;
  padding: 15px;
  box-sizing: border-box;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.message {
  margin-bottom: 10px;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
}

.user {
  background-color: #d1e7dd;
  align-self: flex-end;
  float: right;
  clear: both;
}

.ai {
  background-color: #f8f9fa;
  align-self: flex-start;
  float: left;
  clear: both;
}

.input-box {
  display: flex;
  gap: 10px;
}

.input-box input {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.input-box button {
  padding: 10px 20px;
  font-size: 14px;
  background-color: #0d6efd;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}
</style>